1 ========================================================================
2 CONSOLE APPLICATION : VBAutomateExcel Project Overview
3 ========================================================================
5 /////////////////////////////////////////////////////////////////////////////
8 The VBAutomateExcel example demonstrates how to use Visual Basic.NET code to
9 create a Microsoft Excel instance, create a workbook, fill data into a
10 specific range, save the workbook, close the Microsoft Excel application and
11 then clean up unmanaged COM resources.
13 Office automation is based on Component Object Model (COM). When you call a
14 COM object of Office from managed code, a Runtime Callable Wrapper (RCW) is
15 automatically created. The RCW marshals calls between the .NET application
16 and the COM object. The RCW keeps a reference count on the COM object. If
17 all references have not been released on the RCW, the COM object of Office
18 does not quit and may cause the Office application not to quit after your
19 automation. In order to make sure that the Office application quits cleanly,
20 the sample demonstrates two solutions.
22 Solution1.AutomateExcel demonstrates automating Microsoft Excel application
23 by using Microsoft Excel Primary Interop Assembly (PIA) and explicitly
24 assigning each COM accessor object to a new varaible that you would
25 explicitly call Marshal.FinalReleaseComObject to release it at the end.
27 Solution2.AutomateExcel demonstrates automating Microsoft Excel application
28 by using Microsoft Excel PIA and forcing a garbage collection as soon as the
29 automation function is off the stack (at which point the RCW objects are no
30 longer rooted) to clean up RCWs and release COM objects.
33 /////////////////////////////////////////////////////////////////////////////
36 You must run this code sample on a computer that has Microsoft Excel 2007
40 /////////////////////////////////////////////////////////////////////////////
43 The following steps walk through a demonstration of the Excel automation
44 sample that starts a Microsoft Excel instance, creates a workbook, fills
45 data into a specified range, saves the workbook, and quits the Microsoft
46 Excel application cleanly.
48 Step1. After you successfully build the sample project in Visual Studio 2008,
49 you will get the application: VBAutomateExcel.exe.
51 Step2. Open Windows Task Manager (Ctrl+Shift+Esc) to confirm that no
54 Step3. Run the application. It should print the following content in the
55 console window if no error is thrown.
57 Excel.Application is started
58 A new workbook is created
59 The active worksheet is renamed as Report
60 Filling data into the worksheet ...
61 Save and close the workbook
62 Quit the Excel application
64 Excel.Application is started
65 A new workbook is created
66 The active worksheet is renamed as Report
67 Filling data into the worksheet ...
68 Save and close the workbook
69 Quit the Excel application
71 Then, you will see two new workbooks in the directory of the application:
72 Sample1.xlsx and Sample2.xlsx. Both workbooks have a worksheet named "Report".
73 The worksheet has the following data in the range A1:C6.
75 First Name Last Name Full Name
80 Adam Johnson Adam Johnson
82 Step4. In Windows Task Manager, confirm that the Excel.exe process does not
83 exist, i.e. the Microsoft Excel intance was closed and cleaned up properly.
86 /////////////////////////////////////////////////////////////////////////////
89 VBAutomateExcel - CSAutomateExcel - CppAutomateExcel
91 These examples automate Microsoft Excel to do the same thing in different
92 programming languages.
95 /////////////////////////////////////////////////////////////////////////////
98 Step1. Create a Console application and reference the Excel Primary Interop
99 Assembly (PIA). To reference the Excel PIA, right-click the project and
100 click the "Add Reference..." button. In the Add Reference dialog, navigate to
101 the .NET tab, find Microsoft.Office.Interop.Excel 12.0.0.0 and click OK.
103 Step2. Import and rename the Excel interop namepace:
105 Imports Excel = Microsoft.Office.Interop.Excel
107 Step3. Start up an Excel application by creating an Excel.Application object.
109 Dim oXL As New Excel.Application
111 Step4. Get the Workbooks collection from Application.Workbooks and call its
112 Add function to create a new workbook. The Add function returns a Workbook
118 Step5. Get the active worksheet by calling Workbook.ActiveSheet and set the
121 oSheet = oWB.ActiveSheet
122 oSheet.Name = "Report"
124 Step6. Construct a two-dimensional array containing some first name and last
125 name data and assign it to the Value2 property of a worksheet range. The
126 array's content will appear in the range.
128 Dim saNames(,) As String = {{"John", "Smith"}, _
134 oRng1 = oSheet.Range("A2", "B6")
135 oRng1.Value2 = saNames
137 Step7. Use formula to generate Full Name column from first name and last name
138 by setting range's Formula property.
140 oRng2 = oSheet.Range("C2", "C6")
141 oRng2.Formula = "=A2 & "" "" & B2"
143 Step8. Call workbook.SaveAs method to save the workbook as a local file.
144 Then, call workbook.Close to close the workbook and call application.Quit to
145 quit the application.
147 oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook)
150 Step9. Clean up the unmanaged COM resource. To get Excel terminated rightly,
151 we need to call Marshal.FinalReleaseComObject() on each COM object we used.
152 We can either explicitly call Marshal.FinalReleaseComObject on all accessor:
154 ' See Solution1.AutomateExcel
155 If Not oRng2 Is Nothing Then
156 Marshal.FinalReleaseComObject(oRng2)
159 If Not oRng1 Is Nothing Then
160 Marshal.FinalReleaseComObject(oRng1)
163 If Not oCells Is Nothing Then
164 Marshal.FinalReleaseComObject(oCells)
167 If Not oSheet Is Nothing Then
168 Marshal.FinalReleaseComObject(oSheet)
171 If Not oWB Is Nothing Then
172 Marshal.FinalReleaseComObject(oWB)
175 If Not oWBs Is Nothing Then
176 Marshal.FinalReleaseComObject(oWBs)
179 If Not oXL Is Nothing Then
180 Marshal.FinalReleaseComObject(oXL)
184 and/or force a garbage collection as soon as the calling function is off the
185 stack (at which point these objects are no longer rooted) and then call
186 GC.WaitForPendingFinalizers.
188 ' See Solution2.AutomateExcel
190 GC.WaitForPendingFinalizers()
191 ' GC needs to be called twice in order to get the Finalizers called
192 ' - the first time in, it simply makes a list of what is to be
193 ' finalized, the second time in, it actually is finalizing. Only
194 ' then will the object do its automatic ReleaseComObject.
196 GC.WaitForPendingFinalizers()
199 /////////////////////////////////////////////////////////////////////////////
202 MSDN: Excel 2007 Developer Reference
203 http://msdn.microsoft.com/en-us/library/bb149067.aspx
205 How to automate Microsoft Excel from Visual Basic
206 http://support.microsoft.com/kb/219151
208 How to terminate Excel process after automation
209 http://blogs.msdn.com/geoffda/archive/2007/09/07/the-designer-process-that-would-not-terminate-part-2.aspx
211 How to use Automation to get and to set Office Document properties with
213 http://support.microsoft.com/kb/303294/
216 /////////////////////////////////////////////////////////////////////////////